package com.wdf.rule.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.wdf.rule.drools.DynamicRuleGlobal;
import com.wdf.rule.drools.FuRuleDynamicClassLoader;
import com.wdf.rule.param.RuleParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangdingfu
 * @date 2023-11-16 18:01:49
 */
@RestController
@RequestMapping("/rule")
@RequiredArgsConstructor
public class DynamicRuleController {


    @PostMapping("/executeRule")
    public String executeRule(@RequestBody RuleParam ruleParam) throws ClassNotFoundException {
        //加载class
        FuRuleDynamicClassLoader.INSTANCE.storeClass(ruleParam.getRuleBeanPkg(), FileUtil.file("/Users/wangdingfu/fu-rule-example/classes/OrderInfo.class"));
        Class<?> beanClass = FuRuleDynamicClassLoader.INSTANCE.loadClass(ruleParam.getRuleBeanPkg());
        Object bean = JSONUtil.toBean(ruleParam.getRuleData(), beanClass);
        DynamicRuleGlobal dynamicRuleGlobal = new DynamicRuleGlobal();
        KieHelper kieHelper = new KieHelper();
        kieHelper.setClassLoader(FuRuleDynamicClassLoader.INSTANCE);
        kieHelper.addContent(ruleParam.getRuleContent(), ResourceType.DRL);
        Results results = kieHelper.verify();
        List<Message> messages = results.getMessages();
        if (CollectionUtils.isNotEmpty(messages)) {
            return messages.stream().map(Message::getText).collect(Collectors.joining(";"));
        }
        KieContainer kieContainer = kieHelper.getKieContainer();
        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(bean);
        kieSession.setGlobal("globalData", dynamicRuleGlobal);
        kieSession.fireAllRules();
        kieSession.dispose();
        return "执行成功";
    }


}
